package com.example.financecollegeorderdish.ui

import android.app.Activity
import android.content.Intent
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.blankj.utilcode.util.ClickUtils
import com.bumptech.glide.Glide
import com.drake.brv.utils.grid
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.example.financecollegeorderdish.AppApplication
import com.example.financecollegeorderdish.R
import com.example.financecollegeorderdish.databinding.ActivityManageDishBinding
import com.example.financecollegeorderdish.db.bean.DishBean
import com.example.financecollegeorderdish.vm.ManageDishViewModel
import com.lxj.xpopup.XPopup
import com.wuhao.lib_base.mvvm.v.BaseActivity
import com.wuhao.lib_common.utils.LoggerHelper
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.functions.Consumer
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.serialization.json.Json
import me.rosuh.filepicker.config.FilePickerManager


class ManageDishActivity : BaseActivity<ActivityManageDishBinding, ManageDishViewModel>() {
    override val mViewModel: ManageDishViewModel
            by lazy { ManageDishViewModel() }

    /**
     * 创建 [ViewBinding] 实例
     */
    override fun createVB(): ActivityManageDishBinding =
        ActivityManageDishBinding.inflate(layoutInflater)

    /**
     * 2-订阅 [LiveData]
     */
    override fun initObserve() {
        mViewModel.rvListData.observe(this) {
            mBinding.dishesRv.models = it
        }
    }

    /**
     * 3-用于在页面创建时进行请求接口
     */
    override fun initRequestData() {
    }

    /**
     * 1-初始化 View
     */
    override fun ActivityManageDishBinding.initView() {
        mBinding.inputDish.setOnClickListener(object : ClickUtils.OnDebouncingClickListener() {
            override fun onDebouncingClick(v: View?) {
                startActivity(InputActivity::class.java)
            }
        })
        mBinding.finish.setOnClickListener { finish() }
        mBinding.dishesRv.apply {
            grid(4)
            setup {
                addType<DishBean>(R.layout.rv_item_dish_manage)
                onBind {
                    val model = getModel<DishBean>()
                    findView<TextView>(R.id.name).setText(model.name)
                    findView<TextView>(R.id.price).setText("RMB:${model.price}${getString(R.string.price)}")
                    val dishImg = findView<ImageView>(R.id.dish_img)
                    loadImage(model.imagePath, dishImg)
                }
                onLongClick(R.id.item) {
                    when (it) {
                        R.id.item -> {
                            /*XPopup.Builder(this@ManageDishActivity).asConfirm(
                                "提醒", "确认删除这个菜品吗？"
                            ) {
                                deleteOne(getModel<DishBean>().primaryKey!!)
                            }
                                .show()*/
                            XPopup.Builder(this@ManageDishActivity)
                                .asCenterList(
                                    "请选择一项",
                                    arrayOf<String>("编辑", "删除")
                                ) { position, text ->
                                    when (position) {
                                        0 -> {
                                            InputActivity().start(this@ManageDishActivity,getModel<DishBean>().primaryKey!!)
                                        }
                                        1 -> {
                                            deleteOne(getModel<DishBean>().primaryKey!!)
                                        }
                                        else -> {}
                                    }
                                }
                                .show()

                        }

                        else -> {}
                    }
                }
            }.models = arrayListOf()
        }
    }

    fun deleteOne(id: Long) {
        newRx.add(
            Observable.create<Boolean> { data ->
                val app = application as AppApplication
                val dao = app.room!!.dishBeanDao()
                dao.deleteByPrimaryKey(id)
                val count = dao.countByPrimaryKey(id)
                data.onNext(count > 0)
            }.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
                .subscribe((Consumer<Boolean> { result: Boolean ->
                    if (!result) {
                        showSuccess("删除菜品成功")
                    } else {
                        showError("删除菜品失败")
                    }
                }), (Consumer<Throwable> { throwable: Throwable? ->
                    showError("新增菜品失败")
                })
                )
        )
    }

    val jsonDecoder = Json {
        ignoreUnknownKeys = true // 数据类可以不用声明Json的所有字段
        coerceInputValues = true // 如果Json字段是Null则使用数据类字段默认值
    }

    fun jsonToArray(json: String): String {
        val list = jsonDecoder.decodeFromString<List<String>>(json)
        var result: String = ""
        for (s in list) {
            if (result.isEmpty()) {
                result = s
            } else {
                result += "、${s}"
            }
        }
        return result
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            FilePickerManager.REQUEST_CODE -> {
                if (resultCode == Activity.RESULT_OK) {
                    val list = FilePickerManager.obtainData()
                    LoggerHelper.e(list.last().toString())
                    // do your work
                } else {
                    showWarning("You didn't choose anything~")
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    /**
     * 加载网络图片
     *
     * @param context   上下文
     * @param url       图片 URL
     * @param imageView 目标 ImageView
     */
    fun loadImage(url: String, imageView: ImageView) {
        //.error(R.mipmap.img_default_xh_target); // 错误图片
        Glide.with(this@ManageDishActivity)
            .load(url)
            .into(imageView)
    }
}